package com.cloudinnov.utils;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;

import com.cloudinnov.logic.impl.GlobalInitLogicImpl;

/**
 * @remark 火灾报警系统信息接收服务
 * @version 1.0
 * 
 */
public class FireAlarmServer {
    static final Logger LOG = LoggerFactory.getLogger(FireAlarmServer.class);
	public static boolean isListen = true;
	public static Object object = null;

	private ServerSocket serverSocket;
	public static AmqpTemplate fireTemplate;

	public FireAlarmServer(AmqpTemplate fireTemplate) {
		FireAlarmServer.fireTemplate = fireTemplate;
	} 

	/**
	 * 开启火灾系统接收服务
	 * 
	 * @param port
	 * @return
	 */
	public void startFireSystem(String port) {
		
		try {
			serverSocket = new ServerSocket(Integer.valueOf(port));
		} catch (IOException e) {
			e.printStackTrace();
			isListen = false;
		}
		if (isListen){
		    LOG.debug("火灾系统接收服务器即将启动，等待客户端的连接,port: " + port);
		    GlobalInitLogicImpl.FIRE_CRE_START_UP = true;//标识火灾警报器启动成功
		}
		while (isListen) {
			try {
				Socket socket;
				socket = serverSocket.accept();
				System.out.println("new socket"); //与火灾告警建立连接
				//成安渝的火灾流程
//				FireAlarmConnect fsc = new FireAlarmConnect(socket);// 收到火灾系统CRT连接
//				fsc.start();
				//宛平的火灾流程
				FireAlarmConnectWanPing fsc2 = new FireAlarmConnectWanPing(socket);
				fsc2.start();
			} catch (IOException e) {
				e.printStackTrace();
				LOG.error(e.toString());
			}
		}
		this.exit();
	}
	
	/**
	 * 退出
	 */
	private void exit() {
		try {
			object = null;
			serverSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
